import React, { Component } from 'react';
import { StyleSheet, View, Image, Platform, TextInput } from "react-native";
import { GLOBAL } from '../../../../config/global';

const scale = GLOBAL.SCALE;

export class HeaderSearch extends Component {
	constructor(props) {
		super(props);
		this.state = {
			keyWord: props.keyWord || '',
			placeholder: props.placeholder || '',
		}
	}

	shouldComponentUpdate (nextProps, nextState) {
		//兼容0.54、0.55版本中iOS输入框不能输入中文
		if (Platform.OS === 'ios') {
			if (this.state.keyWord !== nextState.keyWord) { //keyWord为所要获得的TextInput输入值，
				return false;
			}
		}
		return true;
	};

	componentWillReceiveProps (props) {
		if (!props || !props.keyWord) return;
		this.setState({ keyWord: props.keyWord })
	}
	render () {
		let { keyWord, placeholder } = this.state;
		return (
			<View style={[styles.inputViewStyle, this.props.inputViewStyle ? this.props.inputViewStyle : null]}>
				{this.props.inputLeftIcon ? <Image source={this.props.inputLeftIcon} style={[styles.inputLeftIconStyle, this.props.inputLeftIconStyle ? this.props.inputLeftIconStyle : null]} /> : (null)}
				<TextInput
					ref={"searchInput"}
					style={[styles.inputStyle, this.props.inputStyle ? this.props.inputStyle : null]}
					underlineColorAndroid='transparent'
					maxLength={20}
					value={keyWord}
					placeholder={placeholder}
					placeholderTextColor={this.props.placeholderTextColor ? this.props.placeholderTextColor : '#979797'}
					onChangeText={(txt) => {
						this.props.onChangeText && this.props.onChangeText(txt);
						this.setState({ keyWord: txt })
					}}
					onSubmitEditing={() => {
						this.props.onSubmitEditing && this.props.onSubmitEditing();
					}}
					returnKeyType={'search'}
				/>
			</View >
		);
	}
}

const styles = StyleSheet.create({
	inputViewStyle: {
		marginLeft: 5 * scale,
		alignItems: 'center',
		flex: 1,
		flexDirection: 'row',
		height: 31 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 4,
	},
	inputStyle: {
		padding: 0,
		flex: 1,
		height: 31 * scale,
		fontSize: 12 * scale,
		color: '#979797',
		marginLeft: 3 * scale,
	},
	inputLeftIconStyle: {
		height: 13 * scale,
		width: 13 * scale,
		marginLeft: 10 * scale,
		marginRight: 10 * scale,
	},
	inputRightIconStyle: {
		height: 10 * scale,
		width: 10 * scale,
		marginRight: 10 * scale,
	},
})